﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin;

[Area("Admin")]
[Authorize]
public class ArticleController : Base
{
    private readonly LoginUtil _LoginUtil;
    private readonly ArticleService _articleService;
    private readonly AdminUserService _adminUserService;
    private readonly ArticleCateService _articleCateService;
    private readonly ConfigService _configService;
    private readonly AttmentService _attment;
    private readonly LogService _logService;
    public ArticleController(LoginUtil LoginUtil, ArticleService articleService, ArticleCateService articleCateService,
        LogService logService, AttmentService attmentService, ConfigService configService, AdminUserService adminUserService)
    {
        _LoginUtil = LoginUtil;
        _articleService = articleService;
        _articleCateService = articleCateService;
        _configService = configService;
        _attment = attmentService;
        _logService = logService;
        _adminUserService = adminUserService;
    }

    /// <summary>
    ///  列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Article_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] ArticleQuery query, int limit, int page = 1, int json = 0)
    {
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();
        if (json == 1)
        {
            ArticleQuery articleQuery = new()
            {
                Cid = query.SearchCid ?? query.Cid,
                CurrentPage = page,
                Limit = limit,
                Uid = adminUser.UserId,
                Title = query.Title,
                FullTextSwitch = query.FullTextSwitch,
                NickName = query.NickName,
                StartDate = query.StartDate,
                EndDate = query.EndDate,
                MarkStatus = query.MarkStatus,
                Uids = await _adminUserService.AdminPostAsUids(adminUser)
            };
            var pagedList = await _articleService.GetListByCidAdminAsync(articleQuery);
            return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
        }
        ViewBag.cid = query.Cid;
        ViewBag.userGid = adminUser.Gid;
        ViewBag.userId = adminUser.UserId;
        ViewBag.PostCode = adminUser.PostCode;

        ViewBag.catelist = await _articleCateService.CategoryListAsync(adminUser.DeptId, adminUser.Gid, (int)ModelTypeEnum.ModelType.信息报送管理);
        return View();

    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Article_AddOrEdit)]
    public async Task<IActionResult> AddOrEditAsync(int id, int print = 0,int preview=0, int edit = 0, int cid = 0)
    {
        if (edit == 1)
        {
            EditArticleAndContent data = await _articleService.GetEditAsync(id);
            List<ViewAttment> attments = null;
            if (!string.IsNullOrEmpty(data.Attments))
                attments = await _attment.GetListAsync(data.Attments);
            return Json(new { status = 1, data, attments });
        }
        else
        {
            //推测文号
            ViewBag.docNumber = await _articleService.GetArticleByCidAsync(cid);
            //查询自己最新一条
            ViewBag.getByUid = await _articleService.GetByUidAsync(await _LoginUtil.LoginUserId(), cid);
        }
        //附件信息
        SytemConfig configSiteInfo = await _configService.GetByNameAsync();
        ViewBag.fileExts = configSiteInfo.FileExt;
        ViewBag.fileSize = configSiteInfo.FileSize;

        //栏目信息
        ArticleCate articleCate = await _articleCateService.GetInfo(cid);
        ViewBag.cateInfo = articleCate;

        //内容信息
        ViewBag.id = id;

        if (print == 1) return View("Print");
        if (preview == 1) return View("Preview");
        else return View();
    }

    [HttpPost, ActionName("CreatePost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Article_AddOrEdit)]
    [Log(Name = "新增信息报送")]
    public async Task<IActionResult> CreatePostAsync(EditArticleAndContent articlePost)
    {

        if (ModelState.IsValid)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();
            articlePost.Uid = adminUser.UserId;
            Article articleRes = await _articleService.InsertArticleAndContentAsync(articlePost.AsArticle(), articlePost.AsArticleContent());

            if (articleRes.Id > 0)
            {
                return Json(new { status = 1, msg = "新增信息报送 Id: " + articleRes.Id + articleRes.Title, cid = articleRes.Cid });
            }
            else
                return Json(new { status = 0, msg = "新增失败！" });
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { result = 0, msg = error });
        }
    }


    [HttpPost, ActionName("EditPost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Article_AddOrEdit)]
    [Log(Name = "修改信息报送")]

    public async Task<IActionResult> EditPostAsync(EditArticleAndContent articlePost)
    {
        if (ModelState.IsValid)
        {
            UserInfo userInfo = await _LoginUtil.UserInfoAsync();
            if (userInfo.Gid != 1 && userInfo.UserId != articlePost.Uid)
                return Json(new { status = 0, msg = "不能修改别人的内容！" });

            if (0 < await _articleService.UpdateArticleAndContentAsync(articlePost.AsArticle(), articlePost.AsArticleContent()))
            {
                return Json(new { status = 1, msg = "修改信息报送 ID：" + articlePost.Id + articlePost.Title, cid = articlePost.Cid });
            }
            else
            {
                return Json(new { status = 0, msg = "修改失败！" });
            }
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { status = 0, msg = error });
        }
    }

    [HttpPost]
    [ActionPermissionFilter(Permission = PermissionKeys.Article_Delete)]
    [Log(Name = "删除信息报送")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _articleService.DelArticleAndContentAsync(id) > 0)
        {
            return Json(new { status = 1, msg = "删除信息报送 ID：" + id });
        }
        else
            return Json(new { status = 0, msg = "删除失败！" });
    }



}
